package com.lanyou.esb.cook.proxy.common;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 公共帮助类
 * 
 * @author Davey.wu
 */
public final class CommonUtils {
	/**
	 * 判断是否是IP地址
	 * 
	 * @param addr
	 * @return
	 */
	public static boolean isIP(String source) {
		if (StringUtils.isEmpty(source)) {
			return false;
		}
		String rexp = "^[\\d]{1,3}.{1}[\\d]{1,3}.{1}[\\d]{1,3}.{1}[\\d]{1,3}$";
		Pattern pat = Pattern.compile(rexp);
		Matcher mat = pat.matcher(source);
		return mat.matches();
	}

	/**
	 * 判断是否是正整数
	 * 
	 * @param source
	 * @return
	 */
	public static boolean isInteger(String source) {
		if (StringUtils.isEmpty(source)) {
			return false;
		}
		String rexp = "^[0-9]*$";
		Pattern pat = Pattern.compile(rexp);
		Matcher mat = pat.matcher(source);
		return mat.matches();
	}

	public static String toJson(Object object) throws JedisException,
			JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(object);
	}
	
	public static Object fromJson(String value, Class classes)
			throws JedisException, JsonParseException, JsonMappingException,
			IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (Object) mapper.readValue(value, classes);
	}
}
